#include <node_manager/node_manager.h>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
 
using namespace boost::interprocess;
using namespace std;


Node_manager::Node_manager()
{}

Node_manager::~Node_manager()
{}

bool Node_manager::GetMemoryAddr(void)
{
  	try{
		shared_memory_object ros_shared_memory(open_only, "ros_shared_memory", read_only);
		
		mapped_region mmap(ros_shared_memory, read_only);

		cout << "addr:" << mmap.get_address() << endl;

		return true;
	}
	catch(exception& error){
		cout << "can not get memory address due to " << error.what() << endl;
	}
}

void Node_manager::DestroyMemory(void)
{
	try{
		//remove shared memory object
		shared_memory_object::remove("ros_shared_memory");
	}
	catch(exception& error){
		cout << "can not destroy due to " << error.what() << endl;
	}
}

void Node_manager::CreateMemory(void)
{
	try{
		//create shared memory object
		shared_memory_object ros_shared_memory(create_only, "ros_shared_memory", read_write);
		//set the size of the shared memory
		ros_shared_memory.truncate(1024);
		//map the shared memory to current process
		mapped_region mmap(ros_shared_memory, read_write);
	}
	catch(exception& error){
		cout << "can not create due to " << error.what() << endl;
	}
}

void Node_manager::WriteMemory(string s)
{	
	try{
  	shared_memory_object ros_shared_memory(open_or_create, "ros_shared_memory", read_write);
	//map the shared memory object to current process
	mapped_region mmap(ros_shared_memory, read_write);
  
 	memcpy(mmap.get_address(),s.c_str(),s.size());
	}
	catch(exception& error){
		cout << "can not write due to " << error.what() << endl;
	}
}

void Node_manager::ReadMemory(void)
{
	try{
	//open shared memory object
	shared_memory_object ros_shared_memory(open_only, "ros_shared_memory", read_only);
 
	//map the shared memory object to current process
	mapped_region mmap(ros_shared_memory, read_only);
 
	cout<< "read data: " <<static_cast<char*>(mmap.get_address())<<endl;
	}
	catch(exception& error){
		cout << "can not read due to " << error.what() << endl;
	}
}


void Node_manager::add_node(WoZiJiDingDeLaiDaWoA& ops)
{
    node_buffter.push_back(ops);
}